package com.rpc.netty.protoBuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

  //通道就绪时触发
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {

    System.out.println("客户端ctx" + ctx);

    ctx.writeAndFlush(Unpooled.copiedBuffer("helloServer", CharsetUtil.UTF_8));
  }



  //通道有读取事件后触发
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf byteBuf = (ByteBuf)msg;
    System.out.println("服务器回复的消息"+byteBuf.toString(CharsetUtil.UTF_8));

    System.out.println("服务器地址是"+ctx.channel().remoteAddress());
  }

  //异常发生

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
